import Vue from 'vue'
import Vuex from 'vuex'
import { GET_DATA, SAVE_DATUM, CHANGE_NOW, CHANGE_EXIST, UPLOAD_DATUM } from './mutation-types'
import Axios from 'axios'
import { Base64ToBlob } from '../utils'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    datum: JSON.parse(sessionStorage.getItem('datum')) || [],
    nowData: JSON.parse(sessionStorage.getItem('now')) || {}
  },
  mutations: {
    [GET_DATA](state, payload) {
      state.nowData = payload
    },
    [SAVE_DATUM](state, payload) {
      state.datum.push(payload)
    },
    [CHANGE_NOW](state, payload) {
      state.nowData.src = payload.src
      state.nowData.filename = payload.filename
    },
    [CHANGE_EXIST](state, paylod) {
      state.datum[paylod.index].src = paylod.src
    },
    [UPLOAD_DATUM](state) {
      state.datum.length = 0
    }
  },
  actions: {
    getData({ commit }) {
      return new Promise((resolve, reject) => {
        Axios.get('/api/data').then(function (response) {
          sessionStorage.setItem('now', JSON.stringify(response.data))
          commit('GET_DATA', response.data)
          resolve({ status: 'success', code: 200, msg: '' })
        }).catch(function (error) {
          reject({ status: 'failed', code: 400, msg: error })
        })
      })
    },
    saveDatum({ commit }, payload) {
      commit('CHANGE_NOW', payload)
      commit('SAVE_DATUM', this.state.nowData)
      sessionStorage.setItem('datum', JSON.stringify(this.state.datum))
    },
    uploadDatum({ commit }) {
      return new Promise((resolve, reject) => {
        if (this.state.datum.length !== 0) {
          let formData = new FormData()

          for (let i = 0; i < this.state.datum.length; i++) {
            formData.append('files', Base64ToBlob(this.state.datum[i].src))
            formData.append('text', this.state.datum[i].data)
          }
          let headers = {
            'Content-Type': 'multipart/form-data'
          }
          Axios.post('/api/uploadfiles', formData, { headers: headers }).then(function (response) {
            sessionStorage.removeItem('datum')
            commit('UPLOAD_DATUM')
            resolve({ status: 'success', code: 200, msg: response })
          }).catch(function (error) {
            reject({ status: 'failed', code: 400, msg: error })
          })
        } else {
          reject({ status: 'failed', code: 404, msg: '没有要上传的文件' })
        }
      })
    }
  },
  modules: {
  }
})
